package aufgabe2;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SimpleChaining {
	
	/**
	 * 
	 * @param matches
	 */
	public static void compute(List<Match> matches) {
		double overallmaxscore = 0;
		Match bestmatch = null;
		
		for (int j = 0; j < matches.size(); j++) {
			Match matchJ = matches.get(j);
			
			double maxscore = matchJ.getWeight();
			
			for (int i = 0; i <= j - 2; i++) {
				Match matchI = matches.get(i);
				
				if (matchI.precedes(matchJ) && maxscore < (matchI.getScore() + matchJ.getWeight())) {
					maxscore = matchI.getScore() + matchJ.getWeight();
					matchJ.setPrec(matchI);
				}
			}
			
			matchJ.setScore(maxscore);
			
			if (overallmaxscore < maxscore) {
				overallmaxscore = maxscore;
				bestmatch = matchJ;
			}
		}
		
		printChain(bestmatch);
		System.out.println("# optimal chain with score "+overallmaxscore);
	}
	
	public static List<Match> readMatchesFormFile(String absoluteFilename) {
		Path path = FileSystems.getDefault().getPath(absoluteFilename);
		
		List<Match> s = new ArrayList<Match>();
		
		try {
			BufferedReader reader = Files.newBufferedReader(path, Charset.defaultCharset() );
			String line = null;
			while ( (line = reader.readLine()) != null ) {				
				s.add(Match.createMatchFromString(line));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		Collections.sort(s);
		
		return s;
	}
	
	protected static void printChain(Match m) {
		if (m.getPrec() != null) {
			printChain(m.getPrec());
		}
		System.out.println(m);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {		
		List<Match> s = SimpleChaining.readMatchesFormFile(args[0]);
		
		SimpleChaining.compute(s);
	}
}
